package com.pangu.core.engine.game.action.poker;

import org.apache.commons.lang3.StringUtils;

import com.pangu.core.BMDataContext;
import com.pangu.core.cache.CacheHelper;
import com.pangu.core.engine.game.ChessGameEngine;
import com.pangu.core.engine.game.task.poker.PokerCreateAITask;
import com.pangu.core.statemachine.action.Action;
import com.pangu.core.statemachine.impl.BeiMiExtentionTransitionConfigurer;
import com.pangu.core.statemachine.message.Message;
import com.pangu.web.model.GameRoom;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PokerEnterAction<T, S> implements Action<T, S> {

	/**
	 * 进入房间后开启 ,立即开启游戏
	 */
	@Override
	public void execute(Message<T> message, BeiMiExtentionTransitionConfigurer<T, S> configurer) {
		log.info("开始新的一局游戏===========================================================");
		String room = (String) message.getMessageHeaders().getHeaders().get("room");
		if (StringUtils.isBlank(room)) {
			return;
		}

		GameRoom gameRoom = (GameRoom) CacheHelper.getGameRoomCacheBean().getCacheObject(room,
				BMDataContext.SYSTEM_ORGI);
		// @ FIXME 检查是否有真人：测试阶段逻辑为检查是否有人，没有人的时候解散房间
		if (!BMDataContext.getContext().getBean(ChessGameEngine.class).checkHaveMan(gameRoom.getId(),
				gameRoom.getOrgi())) {
			log.info("该局没有人了，解散该房间·························");
			BMDataContext.getPokerEngine().dismissRoom(gameRoom, gameRoom.getOrgi());
			return;
		}
		if (gameRoom != null) {
			//发送当前玩家到前端
			BMDataContext.getContext().getBean(ChessGameEngine.class).sendTopPlayer(gameRoom, gameRoom.getOrgi());
			
			if (!gameRoom.isCardroom()) {
				CacheHelper.getExpireCache().put(gameRoom.getRoomid(),
						new PokerCreateAITask(0, gameRoom, gameRoom.getOrgi()));
			}
			CacheHelper.getGameRoomCacheBean().put(gameRoom.getId(), gameRoom, gameRoom.getOrgi());
		}
	}
}
